MCV PHP Am I doing the Model right? [closed]
Posted
by
Kosmo
on Stack Overflow
See other posts from Stack Overflow
or by Kosmo
Published on 2012-12-05T19:59:03Z
Indexed on
2012/12/06
17:05 UTC
Read the original article
Hit count: 137
I'm trying to create a basic website using MVC in PHP to learn MVC. Its eventually going to be some sort of social networking website but right now I am trying to create a object that can create, delete, update members. What I've done so far for the Model is in the code below, I figure my Controller will take user input and build the array of data that are then passed to this Model. Am I designing this correctly? Should the Controller be the one building the Arrays?
<?php
class Connection {
private $server;
private $database;
private $user;
private $password;
private $conn;
function __construct($server, $database, $user, $password) {
$this->server = $server;
$this->database = $database;
$this->user = $user;
$this->password = $password;
}
function connect() {
$this->conn = mysql_connect($this->server, $this->user, $this->password) or die(mysql_error());
if (!(mysql_select_db($this->database))) {
throw new Exception("Could not connect to database!");
}
}
function deleteMember($memberId) {
$queryString = "DELETE FROM Members WHERE MemberId=" . $memberId . ';';
if (!mysql_query($queryString)) {
throw new Exception("Failed Deleting Member!");
}
}
function insertMember($columns) {
$queryString = 'INSERT INTO Members';
$keys = '(';
$values = '(';
$count = 0;
foreach($columns as $key => $value) {
$keys .= $key;
$values .= $value;
if (!(++$count == count($columns))) {
$keys .= ',';
$values .= ',';
}
}
$queryString .= $keys . ')' . ' VALUES ' . $values . ');';
if (!mysql_query($queryString, $this->conn)) {
throw new Exception('Failed Inserting Member!');
}
else
{
return mysql_insert_id();
}
}
function updateMember($memberId, $columns) {
$queryString = 'UPDATE Members SET ';
$count = 0;
foreach($columns as $key => $value) {
$queryString .= $key . '=' . $value;
if (!(++$count == count($columns))) {
$queryString .= ', ';
}
}
$queryString .= ' WHERE MemberId=' . $memberId . ';';
if (!mysql_query($queryString)) {
throw new Exception('Failed Updating Member');
}
}
function getMembers() {
$queryString = "SELECT * FROM Members;";
$result = mysql_query($queryString);
$memberArray = array();
$count = 0;
while ($row = mysql_fetch_array($result)) {
$memberArray[$count++] = "Member ID: " . $row['MemberId'] . " Name: " . $row['MemberName'] . " Email: " . $row['MemberEmail'];
}
return $memberArray;
}
function disconnect() {
mysql_close($this->conn);
}
}
© Stack Overflow or respective owner